package com.chen.blue.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.chen.blue.result.R;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * Created By CLT On 2023/12/3.
 */
@SuppressWarnings("all")
public class ExcelUtil {

    /**
     * 导出excel
     *
     * @param response  响应流
     * @param type      导出类型
     * @param fileName  导出文件名
     * @param sheetName
     * @param data      导出的数据集合
     * @param <T>
     */
    public static <T> void export(HttpServletResponse response, Class<T> type, String fileName, String sheetName, List<T> data) {

        try {
            EasyExcel.write(response.getOutputStream(), type)
                    .autoCloseStream(false)
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .sheet(sheetName)
                    .doWrite(data);

            response.addHeader("Content-Disposition", StrUtil.format("{}={}", "attachment;filename", URLEncoder.encode(fileName, "UTF-8")));
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        } catch (Exception e) {
            ServletUtil.renderString(JSONUtil.toJsonStr(R.success("导出失败")), response);
        }

    }


    /**
     * 导入
     *
     * @param file 文件
     * @param type 类型
     * @param <T>
     * @return
     * @throws IOException
     */
    public static <T> List<T> include(MultipartFile file, Class<T> type, HttpServletResponse response) throws IOException {

        try {
            return EasyExcel.read(file.getInputStream(), type, null)
                    .autoCloseStream(false)
                    .doReadAllSync();
        } catch (Exception e) {
            ServletUtil.renderString(JSONUtil.toJsonStr(R.success("导入失败")), response);
            return null;
        }

    }

}
